import React from "react";
import { DownOutlined } from "@ant-design/icons";
import Title from "../../components/Title/Title";
import "./index.css";
import { useNavigate } from "react-router-dom";
import { Space, Modal, Table, Tag, Pagination } from "antd";
import { getorderlist, getLookorder, editorder } from "../../api/order";
import { useState, useEffect } from "react";
import { Button, Col, Form, Input, Row, Select, theme, DatePicker } from "antd";
// 订单部分
const SubmitButton = ({ form, children }) => {
  const [submittable, setSubmittable] = React.useState(false);
  const values = Form.useWatch([], form);
  useEffect(() => {
    form
      .validateFields({
        validateOnly: true,
      })
      .then(() => setSubmittable(true))
      .catch(() => setSubmittable(false));
  }, [form, values]);

  return (
    <Button type="primary" htmlType="submit" disabled={!submittable}>
      {children}
    </Button>
  );
};

const { Option } = Select;
const AdvancedSearchForm = ({ onSearch }) => {
  const onFinish = (values) => {
    onSearch(values);
  };
  const { token } = theme.useToken();
  const [form] = Form.useForm();
  const [expand, setExpand] = useState(false);
  const formStyle = {
    maxWidth: "none",
    background: token.colorFillAlter,
    borderRadius: token.borderRadiusLG,
    padding: 24,
  };





  // 这是定义时间的
  const { RangePicker } = DatePicker;
  const getFields = () => {
    const children = [];
    children.push(
      <Col span={8} key={0}>
        <Form.Item
          name="orderNo"
          label="订单号"
          // rules={[
          //   {
          //     required: true,
          //     message: "Please input Order Number!",
          //   },
          // ]}
        >
          <Input placeholder="请输入订单号" />
        </Form.Item>
      </Col>
    );
    children.push(
      <Col span={8} key={0}>
        <Form.Item
          name="consignee"
          label="收货人"
          // rules={[
          //   {
          //     required: true,
          //     message: "Please input Order Number!",
          //   },
          // ]}
        >
          <Input placeholder="请输入收货人" />
        </Form.Item>
      </Col>
    );
    children.push(
      <Col span={8} key={0}>
        <Form.Item
          name="phone"
          label="手机号"
          // rules={[
          //   {
          //     required: true,
          //     message: "Please input Order Number!",
          //   },
          // ]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>
      </Col>
    );

    children.push(
      <Col span={8} key={1}>
        <Form.Item
          name="orderState"
          label="订单状态"
          // rules={[
          //   {
          //     required: true,
          //     message: "Please select Order Status!",
          //   },
          // ]}
        >
          <Select placeholder="请选择订单状态">
            <Option value="pending">派送中</Option>
            <Option value="processing">已受理</Option>
            <Option value="completed">已完成</Option>
          </Select>
        </Form.Item>
      </Col>
    );
    children.push(
      <Col span={8} key={1}>
        <Form.Item
          name="orderTime"
          label="选择时间"
          // rules={[
          //   {
          //     required: true,
          //     message: "Please select time!",
          //   },
          // ]}
        >
          <RangePicker />
        </Form.Item>
      </Col>
    );
    return children;
  };

  return (
    <Form
      form={form}
      name="advanced_search"
      style={formStyle}
      onFinish={onFinish}
    >
      <Row gutter={24}>{getFields()}</Row>
      <div
        style={{
          textAlign: "right",
        }}
      >
        <Space size="small">
          <Button type="primary" htmlType="submit" className="search">
            搜索
          </Button>
          <Button type="defualt" htmlType="reset" className="reset" >
            重置
          </Button>
        </Space>
      </div>
    </Form>
  );
};
export default function Order() {
  // 搜索功能的实线
  const [filteredData, setFilteredData] = useState([]);

  // const handleSearch = (values) => {
  //   const filteredResults = data.filter((item) => {
  //     return (
  //       item.orderNo.includes(values.orderNo) &&
  //       item.consignee.startsWith(values.consignee) ||
  //       item.phone.startsWith(values.phone) &&
  //       item.orderState === values.orderState
  //     );
  //   });
  //  console.log(filteredResults);
  //   setFilteredData(filteredResults);
  // };

  
//   const handleSearch = (values) => {
//     const { orderNo, consignee, phone, orderState } = values;
//     let filteredResults = data;
    
//     if (orderNo || consignee || phone || orderState) {
//       filteredResults = filteredResults.filter(item => 
//         (orderNo ? item.orderNo.includes(orderNo) : true) && 
//         (consignee ? item.consignee.includes(consignee) : true) && 
//         (phone ? item.phone.includes(phone) : true) && 
//         (orderState ? item.orderState === orderState : true)
//       );
//     }
   
//     console.log(filteredResults);
//     setFilteredData(filteredResults);
// };

  const handleSearch = (values) => {
    const { orderNo, consignee, phone, orderState } = values;
    let filteredResults = data;
    
    if (orderNo && consignee && phone && orderState) {
      filteredResults = filteredResults.filter(item => item.orderNo.includes(orderNo) && item.consignee.includes(consignee) && item.phone.includes(phone) && item.orderState.includes(orderState));
    } else {
      if (orderNo) {
        filteredResults = filteredResults.filter(item => item.orderNo.includes(orderNo));
      }
      if (consignee) {
        filteredResults = filteredResults.filter(item => item.consignee.includes(consignee));
      }
      if (phone) {
        filteredResults = filteredResults.filter(item => item.phone.includes(phone));
      }
      if (orderState) {
        filteredResults = filteredResults.filter(item => item.orderState === orderState);
      }
    }
   
    console.log(filteredResults);
    setFilteredData(filteredResults);
};


  const navigate = useNavigate();
  const [lookDetailVisible, setDetailVisible] = useState(false);
  const [lookDetail, setDetail] = useState(null);
  // 来存放获取道到的详情
  const [orderDetails, setOrderDetails] = useState([]);

  const showDetail = async (id) => {
    try {
      const res = await getLookorder(id);
      console.log("Response from getLookorder:", res); // 检查API返回的数据
      console.log(res.data.data);

      setOrderDetails(res.data.data); // Assuming the response contains order details
      setDetail(id);
      setDetailVisible(true);
    } catch (error) {
      console.error("Error fetching order details:", error);
    }
  };

  // 编辑操作
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState(null);

  const showEditModal = (user) => {
    setEditingUser(user);
    setEditModalVisible(true);

  };

  const handleEditSubmit = async (editedUser) => {
    try {
      const res = await editorder(editedUser);
      console.log(res.data);
      if (res.data.code===0) {
        // After a successful edit, fetch the updated order list
        const updatedData = data.map((user) =>
          user.id === editedUser.id ? editedUser : user
        );
        setData(updatedData);

        setEditModalVisible(false);
        fetchData();

        // Fetch the updated order list
        const updatedOrderList = await getorderlist({ currentPage, pageSize });
        if (Array.isArray(updatedOrderList.data.data)) {
          setData(updatedOrderList.data.data);
        }
        fetchData();
        // navigate('/order')
      }
    } catch (error) {
      console.error(error);
    }
  };

  const EditUserForm = ({ user, onSubmit }) => {
    // const [id,setId] = useState(user?user.id:"")
    const [orderNo, setOrderNo] = useState(user ? user.orderNo : "");
    const [orderTime, setOrderTime] = useState(user ? user.orderTime : "");
    const [phone, setPhone] = useState(user ? user.phone : "");
    const [consignee, setConsignee] = useState(user ? user.consignee : "");
    const [deliverAddress, setDeliverAddress] = useState(
      user ? user.deliverAddress : ""
    );
    const [deliveryTime, setDeliveryTime] = useState(
      user ? user.deliveryTime : ""
    );
    const [remarks, setRemarks] = useState(user ? user.remarks : "");
    const [orderAmount, setOrderAmount] = useState(
      user ? user.orderAmount : ""
    );
    const [orderState, setOrderState] = useState(user ? user.orderState : "");

    const handleSubmit = (e) => {
      e.preventDefault();
      onSubmit({
        id: user.id,
        orderNo,
        orderTime,
        phone,
        consignee,
        deliverAddress,
        deliveryTime,
        remarks,
        orderAmount,
        orderState,
      });
    };

    return (
      <Form onSubmit={handleSubmit}>
        <Form.Item label="订单号">
          <Input value={orderNo} onChange={(e) => setOrderNo(e.target.value)} />
        </Form.Item>
        <Form.Item label="下单时间">
          <Input
            value={orderTime}
            onChange={(e) => setOrderTime(e.target.value)}
          />
        </Form.Item>
        <Form.Item label="电话">
          <Input value={phone} onChange={(e) => setPhone(e.target.value)} />
        </Form.Item>
        <Form.Item label="收货人">
          <Input
            value={consignee}
            onChange={(e) => setConsignee(e.target.value)}
          />
        </Form.Item>
        <Form.Item label="送货地址">
          <Input
            value={deliverAddress}
            onChange={(e) => setDeliverAddress(e.target.value)}
          />
        </Form.Item>
        <Form.Item label="送达时间">
          <Input
            value={deliveryTime}
            onChange={(e) => setDeliveryTime(e.target.value)}
          />
        </Form.Item>
        <Form.Item label="备注">
          <Input value={remarks} onChange={(e) => setRemarks(e.target.value)} />
        </Form.Item>
        <Form.Item label="订单金额">
          <Input
            value={orderAmount}
            onChange={(e) => setOrderAmount(e.target.value)}
          />
        </Form.Item>
        <Form.Item label="订单状态">
          <Input
            value={orderState}
            onChange={(e) => setOrderState(e.target.value)}
          />
        </Form.Item>
        <Button type="primary" htmlType="submit" onClick={handleSubmit}>
          提交
        </Button>
      </Form>
    );
  };
  // 定义的订单列表
  const columns = [
    {
      title: "订单号",
      dataIndex: "orderNo",
      key: "orderNo",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "下单时间",
      dataIndex: "orderTime",
      key: "orderTime",
    },
    {
      title: "联系电话",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "收货人",
      key: "consignee",
      dataIndex: "consignee",
    },
    {
      title: "送货地址",
      key: "deliverAddress",
      dataIndex: "deliverAddress",
    },
    {
      title: "送达时间",
      key: "deliveryTime",
      dataIndex: "deliveryTime",
    },
    {
      title: "备注",
      key: "remarks",
      dataIndex: "remarks",
    },
    {
      title: "订单金额",
      key: "orderAmount",
      dataIndex: "orderAmount",
    },
    {
      title: "订单状态",
      key: "orderState",
      dataIndex: "orderState",
    },
    {
      title: "Action",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button type="defualt" onClick={() => showDetail(record)}>
            查看
          </Button>
          <Button type="" onClick={() => showEditModal(record)}>
            编辑
          </Button>
        </Space>
      ),
    },
  ];

  const [data, setData] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(4);
  const fetchData = async () => {
    try {
      const res = await getorderlist({ currentPage, pageSize });
      if (Array.isArray(res.data.data)) {
        setData(res.data.data);
        console.log(res.data);
      }
    } catch (error) {
      console.error("Error fetching goods:", error);
    }
  };


  useEffect(() => {
    fetchData();
  }, [currentPage, pageSize]);

  const { token } = theme.useToken();
  const listStyle = {
    lineHeight: "450px",
    textAlign: "center",
    background: token.colorFillAlter,
    borderRadius: token.borderRadiusLG,
    marginTop: 16,
  };
  return (
    <>
      <div className="dd">
        <Title title="订单管理"></Title>

        <AdvancedSearchForm onSearch={handleSearch} />

        <div style={listStyle}>
          <Table
            columns={columns}
            dataSource={filteredData.length > 0 ? filteredData : data}
            pagination={false}
            className="ordertable"
          />
          <div className="page3">
            <Pagination
              current={currentPage}
              total={500}
              onChange={(page) => setCurrentPage(page)}
              onShowSizeChange={(current, size) => setPageSize(size)}
            />
          </div>
        </div>

        <Modal
          title="订单详情"
          visible={lookDetailVisible}
          onCancel={() => setDetailVisible(false)}
          footer={null}
        >
          {orderDetails && (
            <div className="detail" style={{ display: "flex", flexDirection: "column" }}>
              <div>订单号: {orderDetails.orderNo}</div>
              <div>下单时间: {orderDetails.orderTime}</div>
              <div>联系电话: {orderDetails.phone}</div>
              <div>收货人: {orderDetails.consignee}</div>
              <div>送货地址: {orderDetails.deliverAddress}</div>
              <div>送达时间: {orderDetails.deliveryTime}</div>
              <div>备注: {orderDetails.remarks}</div>
              <div>订单金额: {orderDetails.orderAmount}</div>
              <div>订单状态: {orderDetails.orderState}</div>
            </div>
          )}
        </Modal>

        <Modal
          title="修改订单"
          visible={editModalVisible}
          onCancel={() => setEditModalVisible(false)}
          footer={null}
        >
          <EditUserForm user={editingUser} onSubmit={handleEditSubmit} />
        </Modal>
      </div>
    </>
  );
}
